<?php

namespace App\Models;

use App\Exceptions\Arr;
use Dcat\Admin\Traits\HasDateTimeFormatter;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class AppointQueue extends Model
{
	use HasDateTimeFormatter;
    protected $table = 'eb_appoint_queue';
    public static function booted()
    {
        parent::booted();
        static::creating(function ($model){
            $interval_id = $model->interval_id;
            $interval = HospitalAppointInterval::query()->where('id',$interval_id)->first();
            if($interval) {
                $intervals = HospitalAppointInterval::query()
                    ->where('hospital_appoint_id', $interval->hospital_appoint_id)
                    ->orderBy('start', 'asc')
                    ->pluck('id')
                    ->toArray();

                $interval_key = array_search($interval_id, $intervals);
                $interval_key_num = $interval_key+1;
            }else{
                $interval_key_num = 100;
            }
            $listCount =  AppointQueue::query()
                ->where('hospital_id',$model->hospital_id)
                ->where('appoint_date',$model->appoint_date)
                ->where('interval_id',$model->interval_id)
                ->where('type',$model->type)
                ->count();
            $model->num = $interval_key_num.str_pad($listCount, 2, '0', STR_PAD_LEFT);
            $model->sort = $model->num;
        });
    }
    public function skipSort()
    {
        $interval = HospitalAppointInterval::query()->where('id',$this->interval_id)->first();

        //获取当前时段ID
        $time = "15:12";
        $current = HospitalAppointInterval::query()
            ->where('hospital_appoint_id', $interval->hospital_appoint_id)
            ->where('start', '<',$time)
            ->where('end', '>',$time)
            ->orderBy('start', 'asc')
            ->first();
        $intervals = HospitalAppointInterval::query()
            ->where('hospital_appoint_id', $interval->hospital_appoint_id)
            ->orderBy('start', 'asc')
            ->pluck('id')
            ->toArray();
        if($current) {
            $interval_key = array_search($current->id, $intervals);
            $interval_key_num = $interval_key+1;
            $interval_id = $intervals[$interval_key_num];
        }else{
//            $interval_key = array_search($this->interval_id, $intervals);
//            $interval_key_num = $interval_key+1;
//            $interval_id = $intervals[$interval_key_num];
        }


    }
}
